<template>
  <div class="all">
    <!-- <div class="msg_alert" v-show="alert_show">
      <div class="msg_alert_content">
        <span class="msg_alert_title">
          {{alert_show_msg}}
        </span>
        <i class="msg_alert_icon_close" @click="alert_show = false">x</i>
      </div>
    </div> -->
    <div class="top">
      <div class="footer-content extand-help">
        <div class="footer-item">
         <input class="input input_number" v-model="resolution.w" type="number"/>
        </div>
        <div class="footer-item">
          <input class="input input_number" v-model="resolution.h" type="number"/>
        </div>       
      </div>
    </div>
    <div class="middle">
      <div class="game-main">
        <div class="game-pic" id="game-pic">
          <div id="bgImg">
            <img
              :src="device_url"
              width="100%"
              height="100%"
              @click.stop="setPos($event)"
              @error="loadImageFaild"
            />
          </div>
          <div
            class="click-helper"
            id="click-locate-area"
            v-show="mode == 'click'"
          >
            <div class="block-circle click-circle-area">
              <img
                style="width: 75%; height: 75%; border: none"
                src="/img/click-icon.png"
              />
            </div>
          </div>
          <div
            class="drag-helper"
            id="drag-locate-start-area"
            v-show="mode == 'swipe' || mode == 'fastSwipe'"
          >
            <div class="block-circle drag-circle-start">
              <img
                style="width: 75%; height: 75%; border: none"
                src="/img/drag-start-icon.png"
              />
            </div>
          </div>
          <div
            class="drag-helper"
            id="drag-locate-end-area"
            v-show="mode == 'swipe' || mode == 'fastSwipe'"
          >
            <div class="block-circle drag-circle-end">
              <img
                style="width: 75%; height: 75%; border: none"
                src="/img/drag-end-icon.png"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="opera">

      <div class="footer-content toolbar">
        <div class="footer-item">
          <div @click.stop="fastSwith">{{ modeName }}</div>
        </div>
        <div class="footer-item">
          <div @click.stop="doAsyncImage">同步</div>
        </div>
        <div class="footer-item">
          <div @click.stop="showMore">更多操作</div>
        </div>
        <div class="footer-item">
          <span @click.stop="sendCommand">发送</span>
        </div>
      </div>

      <div class="footer-content extand-help extand-help-input" v-show="mode == 'click'">
        <div class="footer-item">
         <input class="input input_number" @change="input_change" v-model="sendArgs.x1" type="number"/>
        </div>
        <div class="footer-item">
          <input class="input input_number" @change="input_change" v-model="sendArgs.y1" type="number"/>
        </div>       
      </div>
      <div class="footer-content extand-help extand-help-input" v-show="mode == 'swipe'">
        <div class="footer-item">
         <input class="input input_number" @change="input_change" v-model="sendArgs.x1" type="number"/>
        </div>
        <div class="footer-item">
          <input class="input input_number" @change="input_change" v-model="sendArgs.y1" type="number"/>
        </div>
        <div class="footer-item">
         <input class="input input_number"  @change="input_change" v-model="sendArgs.x2" type="number"/>
        </div>
        <div class="footer-item">
          <input class="input input_number"  @change="input_change" v-model="sendArgs.y2" type="number"/>
        </div>  
        <div class="footer-item">
          <input class="input input_number"  @change="input_change" v-model="sendArgs.duration" type="number"/>
        </div> 
      </div>

      <div class="footer-content extand-help extand-help-input" v-show="mode == 'input'">
        <div class="footer-item">
         <input class="input input_text" @change="input_change" v-model="sendArgs.text"/>
        </div>      
      </div>

      <div class="footer-content extand-help extand-help-more" v-show="showMoreBtn">
        <div v-for="item in operaMenus" class="footer-content extand-help more-item">
          <button @click.stop="sendCommand(item.action)">{{item.label}}</button>
        </div>
      </div>

    </div>

    <div class="log" v-show="alert_show">
      <h5>{{ alert_time }}</h5>
      <p>
        {{ alert_show_msg }}
      </p>
    </div>
  </div>
</template>

<script>
import { getStore, setStore, unixTimeStamp,timestampToTime } from "@/utils/util";
export default {
  name: "App",
  components: {},
  directives: {},
  data() {
    return {
      io: null,
      lastGetRunPicTime: 0,
      lastRespTime: 0,
      alert_time : '',
      alert_show: false,
      alert_show_msg: '',
      websocket_url: 'ws://wss.okmnb.com',
      // //debug
      // websocket_url: 'ws://m.autophone.com/websocket/',
      device_url:  "/img/test_mobile.png",
      resolution:{
        w:1080,
        h:1920,
      },
      sendArgs:{
        x1: 20,
        y1: 30,
        x2: 90,
        y2: 90,
        duration: 100,
        text: "",
      },
      deviceId: "web_vivo",
      mode: "click",  
      dragClickTime: 0,
      connectState: 0,
      showMoreBtn: false,
      operaMenus: [
        { label: "唤醒/锁定", action: "wakeup" },
        { label: "解锁", action: "unlock" },
        { label: "开启蓝牙", action: "open_bluetooth" },
        { label: "关闭蓝牙", action: "close_bluetooth" },
        { label: "启动APP", action: "start_app" },
        { label: "关闭APP", action: "kill_app" },
        { label: "打开WiFi", action: "open_wifi" },
        { label: "关闭WiFi", action: "close_wifi" },
        { label: "返回桌面", action: "back_to_desktop" },
      ],
      fastMenus: [
        { label: "点击", action: "click" },
        { label: "滑动", action: "swipe" },
        { label: "输入", action: "input" },
      ],
    };
  },
  created() {
    let did = unixTimeStamp();
    this.deviceId = "web_vivo_" + did;
    this.io = this.initSocket();
    if (this.io == null) {
      console.error("web socket can not use");
    } else {
      setTimeout(() => {
        if (this.connectState == 1) {
          this.sendCommand('ask')
        } else {
          //this.io =  this.initSocket();
        }
      }, 1000);
      // setTimeout(() => {
      //   if(this.lastRespTime == 0){
      //     this.connectState = 2
      //     alert("没有找到响应的客户端")
      //   }
      // },10000)
    }
  },
  destroyed() {
    if (this.io != null) {
      this.io.close();
      this.connectState = 2;
    }
  },
  computed: {
    modeName() {
      let mode = this.mode;
      let name = "";
      this.fastMenus.forEach((item) => {
        if (item.action == mode) {
          name = item.label;
        }
      });
      if(name == ""){
        this.operaMenus.forEach((item) => {
          if (item.action == mode) {
            name = item.label;
          }
        });
      }
      if(name == ""){
        name = mode
      }
      return name;
    },
  },
  methods: {
    loadImageFaild(e) {
        console.log("ele",e);
        let img = e.srcElement;
        this.alertShow("图片加载失败: " + img.src +" 还原成原图");
        img.src = "/img/test_mobile.png";
        img.onerror = null; //防止闪图
    },
    updateImage(src) {
      if(src != ''){
        this.device_url = src
        this.alertShow("更新图片路径为:" + src);
        console.log("更新图片路径为:", src);
      }
    },
    updateLastRespTime() {
        this.lastRespTime =  unixTimeStamp();
        //console.log("recv resp at ",this.lastRespTime)
    },
    fastSwith(){
      let fast = ['click','swipe','input'];
      let max_index = fast.length - 1;
      let mode = this.mode
      let index = fast.indexOf(mode)
      let next_index = index + 1
      if(next_index < 0 || next_index > max_index){
        next_index = 0
      }
      this.mode = fast[next_index]
    },
    doAsyncImage(){
      this.sendCommand('get_image')
    },
    showMore(){
      if(this.showMoreBtn) {
        this.showMoreBtn = false;
      }
      else{
        this.showMoreBtn = true;
      }
    },
    alertShow(msg,timeout = 3000){
      this.alert_show_msg = msg;
      this.alert_time = timestampToTime(unixTimeStamp());
      this.alert_show = true;
      // setTimeout(() => {
      //   this.alert_show = false;
      // },timeout)
    },
    sendCommand(mode = null){
      if(this.connectState != 1 || this.io ==  null){
        this.alertShow("websocket 未连接成功");
        return;
      }
      let tn = unixTimeStamp();
      if(mode == null || typeof(mode) == 'object' ){
         mode = this.mode;
      }
      let args = null;
      if(mode == "get_image"){
        if(tn - this.lastGetRunPicTime < 3) {
          this.alertShow("请勿频繁获取图片");
          return;
        }
        this.lastGetRunPicTime = tn;
      }
      if(mode == 'click'){
        args = [this.sendArgs.x1 + '',this.sendArgs.y1 + '']
      }
      if(mode == 'swipe'){
        args = [this.sendArgs.x1 + '',this.sendArgs.y1 + '',this.sendArgs.x2 + '',this.sendArgs.y2 + '',this.sendArgs.duration + '']
      }
      if(mode == 'input'){
        args = [this.sendArgs.text + '']
      }
      let reqInfo = {       
          time: tn,
          command: mode,
      };
      if(args != null) {
        reqInfo.args = args;
      }
      let message = {
            from: this.deviceId,
            device_type: "Web",
            msg_type: "Req",
            req: reqInfo,
      };
      this.alertShow("sendMessage " + JSON.stringify(reqInfo));
      console.log("sendMessage",message);
      this.io.send(JSON.stringify(message));
    },
    input_change(){
      this.adjustPosition()
    },
    adjustPosition() {
      let referenceEle = document.getElementById("bgImg");
      let clickEle = document.getElementById("click-locate-area");
      let dragStartEle = document.getElementById("drag-locate-start-area");
      let dragEndEle = document.getElementById("drag-locate-end-area");
      let fullScreenEle = document.getElementById("fullscreen-helper-area");
      let inputData = JSON.parse(JSON.stringify(this.sendArgs))

      let w_rate = this.resolution.w  / referenceEle.clientWidth
      let h_rate = this.resolution.h  / referenceEle.clientHeight

      if (clickEle) {
        clickEle.style.left =
          Math.floor(inputData.x1 / w_rate) - clickEle.clientWidth / 2 + "px";
        clickEle.style.top =
          Math.floor(inputData.y1 / h_rate) - clickEle.clientHeight / 2 + "px";
      }
      if (dragStartEle) {
        dragStartEle.style.left =
          Math.floor(inputData.x1 / w_rate)  - dragStartEle.clientWidth / 2 + "px";
        dragStartEle.style.top =
          Math.floor(inputData.y1 / h_rate) - dragStartEle.clientHeight / 2 + "px";
      }
      if (dragEndEle) {
        dragEndEle.style.left =
          Math.floor(inputData.x2 / w_rate) - dragEndEle.clientWidth / 2 + "px";
        dragEndEle.style.top =
          Math.floor(inputData.y2 / w_rate)  - dragEndEle.clientHeight / 2 + "px";
      }
      if (fullScreenEle) {
        fullScreenEle.style.left = "0px";
        fullScreenEle.style.top = referenceEle.clientHeight - 35 + "px";
      }
    },
    setPos(e) {    
      let w_rate = this.resolution.w  / e.target.clientWidth
      let h_rate = this.resolution.h  / e.target.clientHeight
      let x = Math.floor(e.offsetX * w_rate);
      let y = Math.floor(e.offsetY * h_rate);

      // let referenceEle = document.getElementById("bgImg");
      // if(referenceEle){
      //   console.log(referenceEle)
      // }
      let inputData = JSON.parse(JSON.stringify(this.sendArgs)) 
      if (this.mode == "click") {
        inputData.x1 = x
        inputData.y1 = y
      } else if (this.mode == "swipe") {
        if (this.dragClickTime % 2 == 0) {
          inputData.x1 = x
          inputData.y1 = y
        } else {
          inputData.x2 = x
          inputData.y2 = y
        }
        this.dragClickTime += 1;
        if (this.dragClickTime >= 100000) {
          this.dragClickTime = 0;
        }
      }
      this.sendArgs = inputData
      this.adjustPosition();
    },
    initSocket() {
      if (WebSocket == undefined) {
        alert("not suppose current Web Browser");
        return null;
      }

      // Create WebSocket connection.
      const socket = new WebSocket(this.websocket_url);

      // Connection opened
      socket.addEventListener("open", (event) => {
        // alert("connect opened!");
        console.log("connect opened!", event);
        this.connectState = 1;
      });

      // Connection opened
      socket.addEventListener("close", (event) => {
        // alert("connect closed!");
        console.error("connect closed!", event);
        this.connectState = 3;
        //socket.send("connect closed");
      });

      // Connection opened
      socket.addEventListener("error", (event) => {
        // alert("connect error!");
        console.error("connect error!", event);
        this.connectState = 2;
        // socket.send("connect error");
      });

      // Listen for messages
      socket.addEventListener("message", (event) => {
        this.onRecvEvent(event);
        //console.log("Message from server ", event.data);
      });
      return socket;
    },
    onRecvEvent(e) {
      let data = e.data;
      try {
        let resp = JSON.parse(data);        
        console.log(resp)
        if (resp.msg_type == "Resp") {
          if (resp.resp) {
            if (resp.resp.ret) {
              this.alertShow("recv msg ok " + resp.resp.content);
              let resp_item = JSON.parse(resp.resp.content);
              if (resp_item.by == "get_image") {
                this.updateImage(resp_item.src);
              }
              // if(resp_item.by == "ask"){
              // }
            }
            this.updateLastRespTime();
          }
        }
      } catch (e) {
        alert("unknown websocket resp. msg:" + e);
      }
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.app {
  height: 100%;
}
.header {
  position: fixed;
  top: 0px;
  left: 0px;
  height: 35px;
  width: 100%;
  color: #fff;
  background-color: #008db9;
  -index: 100;
}
.header-main {
  width: 90%;
  float: left;
}
.header-fullscreen {
  width: 8%;
  float: right;
}
.footer {
  position: fixed;
  bottom: 0px;
  left: 0px;
  height: 35px;
  width: 100%;
  font-size: 120%;
  z-index: 100;
  color: #fff;
  background-color: #008db9;
}

.block-circle {
  padding: 0;
  margin: 0;
  width: 100%;
  opacity: 0.8;
}
.game-pic {
  /* position: relative; */
}
.main-pic {
  /* position: absolute; */
  /* top: 0;
  left: 0; */
  z-index: 3;
}
.locate-icon {
  width: 100%;
  padding: 0;
  margin: 0;
}
.locate-icon-click {
  fill: rgba(0, 0, 0, 0.801);
}

.locate-icon-drag-start {
  fill: rgba(84, 219, 43, 0.801);
}
.locate-icon-drag-end {
  fill: rgba(240, 31, 49, 0.801);
}
.click-helper {
  position: absolute;
  top: 0;
  left: 0;
  width: 25px;
  height: 25px;
  padding: 0;
  margin: 0;
  z-index: 25;
}
.drag-helper {
  position: absolute;
  top: 0;
  left: 0;
  width: 25px;
  height: 25px;
  padding: 0;
  margin: 0;
  z-index: 25;
}
.fullscreen-helper {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 150;
  width: 100%;
  opacity: 0.7;
}
.bottom-left {
  float: left;
}
.bottom-mid {
  float: left;
}
.bottom-right {
  float: right;
}
.icon {
  width: 25px;
}

.game-main {
  position: relative;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  /* min-height: 300px; */
  overflow-y: scroll;
}
.log-main {
  position: relative;
  left: 0;
  top: 20px;
  overflow: hidden;
}
.log-header {
  position: relative;
}
.log-content {
  position: relative;
  font-size: 15px;
  color: #999999;
  text-align: left;
}
.log-content-list {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
.log-content-item-time {
  border-left: solid #5802027a 2px;
  padding: 2px 0 0 6px;
  margin: 6px 0 0 0;
}

.log-content-item-desc {
  padding: 2px 0 6px 0;
  margin: 0px;
  border-bottom: solid #dddddd72 1px;
}

.orange2 {
  color: #feb902 !important;
}
.red2 {
  color: #e08374 !important;
}
.grey {
  color: #777 !important;
}
.top{
  margin: 4px 0;
}
.toolbar {
  /* background-color: #0e092021;
  color: blanchedalmond; */
  text-align: center;
  margin-top: 8px;
  /* line-height: 98%; */
  /* height: 28px; */
}
.footer-content {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
}
.footer-item {
  flex: 0 1 auto;
  align-self: flex-start;
  color: #fff;
  background-color: #1a0d4b;
}
.input{
  display: inline;
}
.input_number{
  width: 42%;
}
.input_text{
  width: 85%;
}
.msg_alert{
    width: 100%;
    padding: 4px 8px;
    margin: 0;
    box-sizing: border-box;
    border-radius: 4px;
    position: relative;
    background-color: #fdf6ec;
    color: #E6A23C;
    overflow: hidden;
    opacity: 1;
    display: flex;
    -webkit-box-align: center;
    align-items: center;
    transition: opacity .2s;
}
.msg_alert_content{
  display: table-cell;
  padding: 0 4px;
}
.msg_alert_title{
  font-size: 10px;
  line-height: 13px;
}
.msg_alert_icon_close{
    color: #C0C4CC;
    font-size: 10px;
    opacity: 1;
    position: absolute;
    top: 6px;
    right: 10px;
    cursor: pointer;
}
.more-item {
  min-width: 45px;
}

.extand-help-input {
  margin-top: 4px;
}
.extand-help-more {
  margin-top: 6px;
}
</style>
